package com.ws.tool;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class JSONUtils {
    public static void toJson(HttpServletResponse response, Object data) 
        throws IOException {
        Gson gson = new Gson();
        String result = gson.toJson(data);
        response.setContentType("text/json; charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");
        PrintWriter out = response.getWriter();
        out.print(result);
        out.flush();
        out.close();
    }
    
    public static <T> T json2Bean(String json, Class<T> clazz) {
		Gson gson = new Gson();
		return gson.fromJson(json, clazz);
	}
	
	/**
	 * 将json解析成Map
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static Map<String, String> json2Map(String jsonStr) {
		GsonBuilder gb = new GsonBuilder();
		Gson g = gb.create();
		Map<String, String> map = g.fromJson(jsonStr,new TypeToken<Map<String, String>>() {}.getType());
		return map;
	}
	/**
	 * list转换成json
	 * @param list
	 */
	public static String listToJson(List list) {
		if (list == null || list.size() < 1) {
			return "{\"total\":" + 0 + ",\"rows\":[{}]}";
		}
		JSONArray ja = JSONArray.fromObject(list);
		String a = "{\"total\":" + list.size() + ",\"rows\":" + ja.toString() + "}";
		return a;
	}
	/**
	 * @description 
	 * @auther wusong
	 * @time 2016-3-14 下午10:01:50
	 */
	public static String mapToJson(Map map){
		Set s = map.keySet();
		Iterator it = s.iterator();
		StringBuffer buffer = new StringBuffer();
		while (it.hasNext()) {
			String key = (String) it.next();
			Object value = map.get(key);
			if(value instanceof String){
				if (StringUtils.isBlank(buffer.toString())) {
					buffer.append("{\"").append(key).append("\":\"").append(value).append("\",");
				}else{
					buffer.append("\"").append(key).append("\":\"").append(value).append("\",");
				}
			}else if(value instanceof Integer){
				if (StringUtils.isBlank(buffer.toString())) {
					buffer.append("{\"").append(key).append(":").append(value).append("\",");
				}else{
					buffer.append("\"").append(key).append(":").append(value).append("\",");
				}
			}
			
		}
		String json = buffer.toString();
		json = json.substring(0, json.length()-1)+"}";
		return json;
	}
}